package com.azt.front.interceptor;

import com.azt.api.service.UserPermissionService;
import com.azt.front.permission.ClearRequire;
import com.azt.front.permission.RequirePermission;
import com.azt.front.permission.RequireType;
import com.azt.front.utils.ContextUtil;
import com.azt.utils.CommonUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 权限拦截器
 * Created by shangwq on 2016/11/8.
 */
public class RequirePermissionInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserPermissionService userPermissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            RequirePermission requirePermission = handlerMethod.getMethodAnnotation(RequirePermission.class);
            ClearRequire clearRequire = handlerMethod.getMethodAnnotation(ClearRequire.class);
            if(clearRequire == null && requirePermission == null) {
                requirePermission = handlerMethod.getBean().getClass().getAnnotation(RequirePermission.class);
            }

            if(requirePermission != null) {
                if(!ContextUtil.isLogined()) {
                    CommonUtil.redirectToLogin(request, response);
                    return false;
                }
                String[] permissions = requirePermission.value();
                RequireType requireType = requirePermission.type();
                if(ArrayUtil.isNotEmpty(permissions)) {
                    if(!userPermissionService.hasThisPerm(ContextUtil.getCurrentRole().getId(), permissions, requireType == RequireType.AND ? 1 : 2)) {
                        //无权限
                        if (CommonUtil.isAjax(request)) {
                            //ajax请求的话则403状态返回错误码
                            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                            CommonUtil.renderJson(response, "未授权");
                        } else {
                            String url = "/noperm";
                            String preUrl = CommonUtil.getPreUrl(request);
                            if (StringUtils.isNotBlank(preUrl)) {
                                try {
                                    url += "?redirect=" + URLEncoder.encode(preUrl, "utf-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                            try {
                                response.sendRedirect(url);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
